/*
 * @Author: zhangwei 1405298045@qq.com
 * @Date: 2022-03-03 21:13:07
 * @LastEditTime: 2022-03-04 14:11:43
 * @LastEditors: zhangwei 1405298045@qq.com
 * @Description:
 * @FilePath: /ll-fe-mp-dyfx/src/utils/srorage/index.js
 *
 */

import srorageKey from './key';
import { Encrypt, Decrypt } from './crypto';

const isProd = process.env.NODE_ENV === 'production';

/**
 * 缓存数据
 * @param key
 * @param data
 * @param expireTime 过期时间 永久
 */
export const setLocal = (key, data, expireTime) => {
	if (!key || !srorageKey[key]) {
		return;
	}

	let formatParams = Object.assign(
		{
			body: data
		},
		expireTime && {
			expireTime: Date.now() + 1000 * 60 * 60 * 24 * expireTime
		}
	);

	formatParams = isProd ? Encrypt(formatParams) : JSON.stringify(formatParams);

	uni.setStorageSync(key, formatParams);
};

/**
 * 获取本地储存
 * @param key
 */
export const getLocal = (key) => {
	if (!key || !srorageKey[key]) {
		return;
	}

	let cacheData = uni.getStorageSync(key);

	if (!cacheData) {
		return;
	}

	isProd && (cacheData = Decrypt(cacheData));

	const { body, expireTime } = JSON.parse(cacheData);

	if (!expireTime || Date.now() < expireTime) {
		return body;
	}

	// 过期删除key
	clearLocal(key);
	return;
};

/**
 * 删除本地储存
 */
export const clearLocal = function (key) {
	if (!key || !srorageKey[key]) {
		return;
	}

	uni.removeStorageSync(key);
};

/**
 * 删除所有缓存
 */
export const clearAllLocal = function (noLogin = false) {
	/* eslint-disable */
	// 判断当前页面路由
	const routes = getCurrentPages();
	const curRoute = routes[routes.length - 1].route;
	const filterRoute = 'pages/tabBar/PersonalCenter';

	const locationInfo = getLocal(srorageKey.locationInfo);
	const locationId = getLocal(srorageKey.locationId);
	const selectAddress = getLocal(srorageKey.selectAddress);

	uni.clearStorageSync();

	locationInfo && setLocal(srorageKey.locationInfo, locationInfo);
	locationId && setLocal(srorageKey.locationId, locationId);
	selectAddress && setLocal(srorageKey.selectAddress, selectAddress);

	//当不需要跳转登陆的时候直接返回
	if (noLogin) {
		return;
	}

	const url = '/authorizePage/WechatAuthorize';
	if (curRoute === filterRoute) {
		uni.navigateTo({
			url
		});
		return;
	}

	uni.redirectTo({
		url
	});
};
